'use strict';
const db = uniCloud.database()
const coll = db.collection('xinyuan')
const coll1 = db.collection('user')
const dbCmd = db.command
exports.main = async (event, context) => {

	//先查询点赞剩余次数
	let res0 = await coll1.where({
		openid: event.openid
	}).get()
	console.log(res0)
	if (res0.data[0].dianzanjihui <= 0) {
		return {
			status: 0,
			msg: '您已无点赞机会'
		}
	} else if (res0.data[0].xinyuan == event.id) {
		return {
			status: 0,
			msg: '不能点赞自己的心愿'
		}
	} else {
		let res3 = await coll1.where({
			dianzanlist: event.id
		}).count()
		console.log(res3)
		if (res3.total > 0) {
			return {
				status: 0,
				msg: '此心愿您已赞过'
			}
		} else {
			let res = await coll.where({
				_id: event.id
			}).update({
				zan: dbCmd.inc(1)
			})

			let res1 = await coll1.where({
				openid: event.openid
			}).update({
				dianzanjihui: dbCmd.inc(-1),
				dianzanlist: dbCmd.push(event.id)
			})
			return {
				status: 1,
				msg: '点赞成功！'
			}
		}



		/* for (let item of res0.data[0].dianzanlist) {
			if (item == event.id) {
				return {
					status: 0,
					msg: '此心愿您已赞过'
				}
			} else {
				let res = await coll.where({
					_id: event.id
				}).update({
					zan: dbCmd.inc(1)
				})

				let res1 = await coll1.where({
					openid: event.openid
				}).update({
					dianzanjihui: dbCmd.inc(-1),
					dianzanlist: dbCmd.push(event.id)
				})
				return {
					status: 1,
					msg: '点赞成功！'
				}
			}
		} */



	}




};
